<template>
	<view class="pd16_15">

		<view class="box over-hide">
			<view class="recharge-header">
				<image :src="statics.moneyRecharge"></image>
				<view class="main pd24_20">
					<view class="ft16 cl-w9">当前余额</view>
					<view class="mt16 ftw600 ft32 cl-w">{{userinfo.money}}</view>
				</view>
			</view>
			<navigator url="/pages/client/vipcard/moneylog">
				<view class="pd16_15 flex alcenter space">
					<text class="ft14 ftw600 cl-w">余额明细 </text>
					<text class="iconfont iconicon_arrow_circle ft20" :style="{color:tempColor}"></text>
				</view>
			</navigator>
		</view>
		<!-- <button class="btn" type="default" @click="paySubs">订阅</button> -->
		<!-- <button class="btn" type="default" @click="payInApp">内购</button> -->
		<radio-group @change="changeNum">
			<view class="flex wrap space mt16">
				<view v-for="(item,index) in list" :key="index" :class="index > 1 ? 'mt16' : ''"
					class="box pd20_15 flex alcenter space" @click="clickNum(item.productId,index,item)"
					style="width: 330rpx; display: flex;flex-direction: column;">
					<view style="display: flex;justify-content: space-between;">
						<!-- <view class="ft16 cl-w ftw600">{{item.name}}</view> -->
						<view class="ft16 cl-w ftw600" style="margin-right: 20px;">
							{{item.oneTimePurchaseOfferDetails.formattedPrice}}
						</view>
						<view class="ft16 cl-w ftw600">
							<radio :value="item.productId" :checked="selectedProduct.productId == item.productId" />
						</view>

					</view>
				</view>
			</view>
		</radio-group>
		<radio-group @change="changetd" style="display: none;">
			<view class="mt16">
				<view v-for="(item,index) in tdList" :key="index" :class="index >= 1 ? 'mt16' : ''"
					class="box pd20_15 flex alcenter space">
					<text class="ft16 cl-main ftw600">{{item.name}}</text>
					<radio :value="item.num" :checked="tdnum == item.num" :color="tempColor" />
				</view>
			</view>
		</radio-group>
		<view v-if="getCoupon > 0" class="mt16 tag-coupon" :style="getTagStyle">
			送价值{{getCoupon}}元优惠券
		</view>
		<!-- <view class="list-call" style="margin-top: 40upx;">
			<input class="sl-input tdadf" v-model="num" type="number" placeholder="自定义金额" />
		</view> -->
		<view class="form-footer-h">
			<view class="form-footer form-footer-h">
				<view class="form-footer-main pd10_15">
					<!-- <button style="width: 49%; float: left;" @click="paykami" class="btn-big">卡密充值</button> -->
					<button style="width: 100%; float: right;" @click="submit" class="btn-big" :style="getBtnStyle">支付
						{{num>0?'$'+num:''}}</button>
				</view>
			</view>
		</view>
		<hFormAlert v-if="cancelShow" title="卡密充值" name="cancel_desc" placeholder="请输入卡密卡号" @confirm="confirm"
			@cancel="cancel"></hFormAlert>
		<dialog-couponshare v-if="showCouponInvite" @closed="closedInvite"></dialog-couponshare>
	</view>
</template>

<script>
	import hFormAlert from '@/components/h-form-alert/h-form-alert.vue';
	var googlePay = uni.requireNativePlugin('sn-googlepay5');
	export default {
		components: {
			hFormAlert
		},
		data() {
			return {
				selectedProduct: {

				},
				isConnected: false,
				num: '',
				list: '',
				moneyList: [{
						num: '30',
						coupon: 0
					},
					{
						num: '50',
						coupon: 0
					},
					{
						num: '100',
						coupon: 0
					},
					{
						num: '200',
						coupon: 0
					},
				],
				tdnum: '901',
				openid: '',
				tdList: [{
						num: '901',
						name: '微信H5(50-100-200)'
					},
					{
						num: '904',
						name: '支付宝H5(30-50-100-200)'
					},
				],
				numa: '',
				userinfo: '',
				showCouponInvite: false,
				cancelShow: false,
				offerToken: ""
			}
		},
		computed: {
			getCoupon() {
				for (var a in this.moneyList) {
					if (this.moneyList[a].num == this.num) {
						return this.moneyList[a].coupon;
					}
				}
				return 0;
			}
		},
		onLoad(e) {
			this.init()

			if (e.price) {
				this.num = e.price
			}
			//#ifdef MP-WEIXIN
			this.wxlogin()
			//#endif
		},
		onShow() {
			// this.ongrzlTap();
		},
		onShareAppMessage(e) {

		},
		onShareTimeline(e) {

		},
		methods: {
			async init() {

				// let params = {
				// 	language: 0
				// }
				// let [err, res] = await this.$httpas.get('/api/cz/list', params);
				// this.list = [{
				// 	money:"$99",
				// 	id:"vip_1002"
				// }]
				// 初始化，参数 { autoReconnect: true}
				googlePay.init({
					autoReconnect: true, // 是否自动重连(插件实现)
					enableAutoServiceReconnection: true, //是否自动重连（8.0+支持）
					enableExternalOffer: true, // 是否启用外部优惠
					enableAlternativeBillingOnly: true //
				}, (e) => {
					if (e.code == 0) {
						this.isConnected = true;
						// 初始化成功
						console.log(e, 'ee');
						var pId = ['vip_1001', 'vip_1003'];
						googlePay.querySku({
								inapp: pId //内购
							},
							(e) => {
								if (e.code == 0) {
									if (e.list && e.list.length > 0) {
										console.log('共查询到 ' + e.list.length + ' 个商品');
										this.list = e.list
										console.log('this.list', this.list);
										// 遍历商品列表
										e.list.forEach((product, productIndex) => {
											// console.log(`\n=== 商品 ${productIndex + 1} 基本信息 ===`);
											// // 提取第一层：商品基本信息
											// const productId = product.productId;
											// const productType = product.productType;
											// const name = product.name;
											// const title = product.title;
											// const description = product.description;
											// console.log('商品ID: ' + productId);
											// console.log('商品类型: ' + productType); // subs表示订阅
											// console.log('商品名称: ' + name);
											// console.log('商品标题: ' + title);
											// console.log('商品描述: ' + description);

											// 提取第二层：订阅优惠详情
											if (product.subscriptionOfferDetails && product
												.subscriptionOfferDetails.length > 0) {
												product.subscriptionOfferDetails.forEach((offer,
													offerIndex) => {
													//      console.log(`优惠方案 ${offerIndex + 1} 信息 ---`);
													//      const basePlanId = offer.basePlanId;
													//      const offerToken = offer.offerToken;
													this.offerToken = offer.offerToken;
													// console.log('this.offerToken',this.offerToken);
													//      const offerTags = offer.offerTags;

													//      console.log('基础方案ID: ' + basePlanId);
													//      console.log('优惠令牌: ' + offerToken);
													//      console.log('优惠标签: ' + (offerTags.length > 0 ? offerTags.join(',') : '无'));

													// 提取第三层：定价阶段信息
													if (offer.pricingPhases && offer
														.pricingPhases.pricingPhaseList) {
														offer.pricingPhases
															.pricingPhaseList.forEach((
																phase, phaseIndex) => {
																// console.log(`定价阶段 ${phaseIndex + 1} 信息 `);

																// const priceCurrencyCode = phase.priceCurrencyCode;
																// const priceAmountMicros = phase.priceAmountMicros;
																// const formattedPrice = phase.formattedPrice;
																// const billingPeriod = phase.billingPeriod;
																// const billingCycleCount = phase.billingCycleCount;
																// const recurrenceMode = phase.recurrenceMode;

																// console.log('货币代码: ' + priceCurrencyCode);
																// console.log('价格(微单位): ' + priceAmountMicros);
																// console.log('显示价格: ' + formattedPrice);
																// console.log('计费周期: ' + billingPeriod + ' (P1M表示每月)');
																// console.log('计费周期数: ' + billingCycleCount + ' (0表示无限循环)');
																// console.log('循环模式: ' + recurrenceMode + ' (1表示自动续期)');
															});


													} else {
														console.log('该优惠方案无定价阶段信息');
													}
												});
											} else {
												console.log('该商品无订阅优惠详情');
											}
										});
									} else {
										console.log('未查询到任何商品数据');
									}
								} else {
									//查询失败
									console.log('querySku fail', e);
								}
							}
						);
					} else {
						this.isConnected = false;
						// 初始化失败
					}
				});
			},
			clickNum(value, index, item) {
				console.log('item', item);
				this.selectedProduct.allVAalue = item //所选参数
				this.selectedProduct.productId = value;
				// this.numa = this.moneyList[index].coupon
			},
			async submit() {
				console.log('this.num', this.selectedProduct);
				var that = this
				// 步骤二：支付
				googlePay.pay({
						productId: this.selectedProduct.productId // 产品id
					},
					(e) => {
						console.log('pay result', e);
						if (e.code != 1) {
							// 步骤三：确认订单
							googlePay.consume({
									purchaseToken: e.data[0].original.purchaseToken
								},
								(e) => {
									console.log('consume result', e);
									that.$httpas.post2({
										data: {
											do: 'cz',
											op: 'googlepay',
											eee: JSON.stringify(e),
											allID: JSON.stringify(that.selectedProduct.allVAalue)
										},
										success: res => {
											uni.showToast({
												title: '' + res,
												icon: 'none'
											});
										}
									})
								}
							);
						} else {
						
						}


					}
				);
				// googlePay.pay({
				// 		productId: this.selectedProduct.productId, // 产品id
				// 		offerToken: this.offerToken
				// 	},
				// 	(e) => {
				// 		console.log('pay result', e);
				// 		if (e.code == 0) {
				// 			// 步骤三：确认订单
				// 			// 支付成功后，一定别忘记调用acknowledge, 参数具体看接口
				// 			googlePay.acknowledge({
				// 					original: e.data[0].original,
				// 					signature: e.data[0].signature
				// 				},
				// 				(e) => {
				// 					console.log('acknowledge result', e);
				// 					that.$httpas.post2({
				// 						data: {
				// 							do: 'cz',
				// 							op: 'googlepay',
				// 							eee: JSON.stringify(e),

				// 						},
				// 						success: res => {
				// 							uni.showToast({
				// 								title: '' + res,
				// 								icon: 'none'
				// 							});
				// 						}
				// 					})
				// 				}
				// 			);
				// 		}
				// 	}
				// );
				// if (!this.num) {
				// 	uni.showToast({
				// 		title: this.$t('text.jinge'),
				// 		icon: "none"
				// 	});
				// 	return false
				// }
				// let params = {
				// 	money: this.num
				// }
				// console.log(params, 'money');
				// params.token = uni.getStorageSync("userinfo").token
				// let [err, res] = await this.$httpas.get('/api/cz/addOrder', params);
				// window.location.href=res.data.data.order.payment_url;
			},
			changeNum(e) {
				this.num = parseInt(e.detail.value);
			},
			changetd(e) {
				this.tdnum = e.detail.value;
			},

		},
		paykami() {
			this.cancelShow = true
		},
		cancel() {
			this.cancelShow = false
		},
		confirm(e) {
			console.log(e.cancel_desc);
			if (!e.cancel_desc) {
				this.cancelShow = false
				uni.showToast({
					title: this.$t('text.placeholders'),
					icon: "none"
				});
				return false
			}
			let data = {};
			data.token = uni.getStorageSync("userinfo").token;
			data.uid = uni.getStorageSync("userinfo").id;
			data.crd = e.cancel_desc;

			uni.request({
				url: this.configs.webUrl + '/api/user/kami',
				data: data,
				success: res => {
					if (res.data.code == 1) {
						this.userinfo.money = res.data.data.userinfo.money
						uni.showToast({
							title: res.data.msg,
							icon: "none"
						});
					} else {
						uni.showToast({
							title: res.data.msg,
							icon: "none"
						});
					}
				},
				fail: (data, code) => {
					//console.log('fail' + JSON.stringify(data));
				}
			});
			this.cancelShow = false
		},
		paySuccess() {

		},
		paywxxcx() {
			if (!this.num) {
				uni.showToast({
					title: this.$t('text.jinge'),
					icon: "none"
				});
				return false
			}
			if (!this.openid) {
				uni.showToast({
					title: 'Openid未加载',
					icon: "none"
				});
				return false
			}
			uni.showLoading({
				title: 'Loading'
			});
			let data = {};
			data.token = uni.getStorageSync("userinfo").token;
			data.total = this.num;
			data.tdnum = this.tdnum;
			data.openid = this.openid;
			uni.request({
				url: this.configs.webUrl + '/api/paywx/paywxxcx',
				data: data,
				success: res => {
					console.log(res.data);
					if (res.data.code == 1) {
						uni.hideLoading();
						uni.requestPayment({
							"provider": 'wxpay',
							"appId": res.data.data.appId,
							"timeStamp": res.data.data.timeStamp + '',
							"nonceStr": res.data.data.nonceStr,
							"package": res.data.data.package,
							"signType": 'MD5',
							"paySign": res.data.data.sign,
							success: function(res1) {
								uni.showModal({
									title: this.$t('play.win'),
									content: this.$t('toast.pay.success'),
									showCancel: false,
									confirmText: this.$t('text.confirm'),
									success: function(res) {
										if (res.confirm) {
											this.ongrzlTap();
										} else if (res.cancel) {

										}
									}
								});
								//uni.showToast({ title: '支付成功',icon:"none" });
								console.log('success:' + JSON.stringify(res1));
							},
							fail: function(err1) {
								uni.showModal({
									title: this.$t('toast.pay.fail'),
									content: JSON.stringify(err1),
									showCancel: false,
									confirmText: this.$t('text.confirm'),
									success: function(res) {
										if (res.confirm) {
											//uni.navigateBack();
										} else if (res.cancel) {

										}
									}
								});
								//uni.showToast({ title: JSON.stringify(err1),icon:"none" });
								console.log('fail:' + JSON.stringify(err1));
							}
						});
					} else {
						uni.hideLoading();
						uni.showModal({
							title: this.$t('play.win'),
							content: JSON.stringify(res.data),
							showCancel: false,
							confirmText: this.$t('text.confirm'),
							success: function(res) {
								if (res.confirm) {
									uni.navigateBack();
								} else if (res.cancel) {

								}
							}
						});
					}
				},
				fail: (data, code) => {
					//console.log('fail' + JSON.stringify(data));
				}
			});
		},
		paySuccessa() {
			if (!this.num) {
				uni.showToast({
					title: this.$t('text.jinge'),
					icon: "none"
				});
				return false
			}
			uni.showLoading({
				title: 'Loading'
			});
			let data = {};
			data.iswx = '';
			//#ifdef H5
			var ua = window.navigator.userAgent.toLowerCase();
			if (ua.match(/MicroMessenger/i) == 'micromessenger') {
				data.iswx = 'wxgzh';
			}
			//#endif
			data.token = uni.getStorageSync("userinfo").token;
			data.total = this.num;
			data.tdnum = this.tdnum;
			// uni.showToast({ title:data.iswx,icon:"none" });
			// return false
			uni.request({
				url: this.configs.webUrl + '/api/paywx/paywxh5',
				data: data,
				success: res => {
					console.log(res);
					if (res.data.code == 1) {
						uni.hideLoading();
						console.log(res.data.data);
						// #ifdef APP-PLUS  

						uni.navigateTo({
							url: '/pages/client/webva?url=' + res.data.data
						})
						//plus.runtime.openURL(res.data.data);
						// #endif  
						// #ifdef H5
						window.open(res.data.data, "_self")
						// #endif 
						///index/paydsf?out_trade_no=2206131027251
						//uni.showToast({ title: res.data.msg,icon:"none" });
					} else {
						uni.hideLoading();
						uni.showToast({
							title: res.data.msg,
							icon: "none"
						});
					}
				},
				fail: (data, code) => {
					//console.log('fail' + JSON.stringify(data));
				}
			});
		},
		async ongrzlTap() {
			let data = {};
			data.token = uni.getStorageSync("userinfo").token;
			data.uid = uni.getStorageSync("userinfo").id;
			uni.request({
				url: this.configs.webUrl + '/api/user/index',
				data: data,
				success: res => {
					if (res.data.code == 1) {
						let ionfo = res.data.data
						ionfo.isLogin = true
						this.userinfo = ionfo
						this.jfdt = ionfo.config.jfdt ? ionfo.config.jfdt : ''
						uni.setStorage({ //缓存配置信息
							key: 'userinfo',
							data: res.data.data
						})
						if (res.data.data.avatar) {
							var str = res.data.data.avatar;
							if (str.indexOf("data:image") != -1) {
								this.avatar = '';
							} else {
								if (str.indexOf("http") != -1) {
									this.avatar = res.data.data.avatar;
								} else {
									this.avatar = this.configs.imgUrl + res.data.data.avatar;
								}
							}
						} else {
							this.avatar = '';
						}
						uni.setStorage({ //缓存配置信息
							key: 'avatar',
							data: this.avatar
						})
					} else {
						uni.showToast({
							title: res.data.msg,
							icon: "none"
						});
					}
				},
				fail: (data, code) => {
					//console.log('fail' + JSON.stringify(data));
				}
			});
		},
		closedInvite() {
			this.showCouponInvite = false;
			let pages = getCurrentPages();
			uni.navigateBack({
				delta: pages.length
			});
		},
		wxlogin() {
			var this_ = this
			uni.login({
				timeout: 10000,
				provider: 'weixin', //如果是uniapp，在这里需要标明平台的类型，支持的参数请查阅uniapp官网的uni.login()文档
				success: (res) => {
					//console.log(res);
					//登陆成功的回调
					uni.request({
						url: this.configs.webUrl + '/api/user/getOpenid',
						method: 'GET',
						data: {
							token: uni.getStorageSync("userinfo").token, //你的小程序的secret,  
							code: res.code //wx.login 登录成功后的code  
						},
						success: (cts) => {
							console.log(cts.data.data);
							if (cts.data.code == 1) {
								this_.openid = cts.data.data.openid
							} else {
								uni.showModal({
									title: this.$t('play.win'),
									content: JSON.stringify(cts.data),
									showCancel: false,
									confirmText: this.$t('text.qd'),
									success: function(res) {
										if (res.confirm) {
											uni.navigateBack();
										} else if (res.cancel) {

										}
									}
								});
							}
						},
						fail: (err1) => {
							console.log(err1);
							//失败的回调
						}
					});

				},
				fail: (err) => {
					console.log(err);
					//登陆失败的回调
				}
			})
		}
	}
</script>

<style>
	.box {
		width: 100%;
		background: #1f1f1f;
		box-shadow: 0rpx 8rpx 40rpx 0rpx rgba(0, 0, 0, 0.04);
		border-radius: 16rpx;
	}

	.tag-coupon {
		width: 100%;
		height: 80rpx;
		border-radius: 16rpx;
		text-align: center;
		line-height: 80rpx;
		font-size: 28rpx;
	}

	.recharge-header {
		height: 240rpx;
		width: 100%;
		position: relative;
	}

	.recharge-header image {
		width: 100%;
		height: 240rpx;
	}

	.recharge-header .main {
		position: absolute;
		width: 100%;
		height: 240rpx;
		left: 0;
		top: 0;
	}

	.tdadf {
		border: 1px solid #1f1f1f;
		padding: 10px 10px;
		text-align: center;
		height: 80upx;
		background: #1f1f1f;
		border-radius: 8px;
		box-shadow: 0px 4px 20px 0px rgba(0, 0, 0, 0.04);
		font-size: 30upx;
		color: #fff;
	}
</style>